package com.lzh.shellcommand.commands

import org.apache.commons.lang3.StringUtils
import org.springframework.shell.standard.ShellComponent
import org.springframework.shell.standard.ShellMethod


@ShellComponent("local")
class Local {

    @ShellMethod(key = ["ps"], value = "显示运行中的 spring boot")
    fun ps() {
        val data: Array<Array<String>> = localJmxConn().mapNotNull {
            it.use { conn ->
                val runtimeMXBean = conn.rmxb()
                when {
                    isSpringBootApplication(runtimeMXBean) -> {
                        val memoryMXBean = conn.mmxb()
                        val heapMemoryUsage = memoryMXBean.heapMemoryUsage
                        val heapUsage = "${heapMemoryUsage.used / (1000 * 1000)}MB/${heapMemoryUsage.max / (1000 * 1000)}MB"
                        val pid = runtimeMXBean.systemProperties["PID"] ?: ""
                        val javaVersion = runtimeMXBean.systemProperties["java.version"] ?: ""
                        val running = runtimeMXBean.systemProperties["sun.java.command"]?.
                                substring(runtimeMXBean.systemProperties["sun.java.command"]?.lastIndexOf(".")!! + 1)
                                ?: ""
                        val start = processUserFriendlyTime(System.currentTimeMillis() - runtimeMXBean.startTime)
                        val ports = getPorts(pid)
                        /**
                         * "PID","MAIN","RUNNING","HEAP","PORT","PATH","JAVA_VERSION"
                         */
                        return@mapNotNull arrayOf(pid, running, start, heapUsage, ports, StringUtils.abbreviate(runtimeMXBean.classPath, 50), javaVersion)
                    }
                    else -> return@mapNotNull null
                }
            }
        }.toTypedArray()
        printPsTable(data)
    }


    @ShellMethod(key = ["kill"], value = "kill spring boot")
    fun kill(pid: String) {
        "kill -9 $pid".command()
        println("kill pid $pid success")
    }


}